/****Created by song****/
(function(win) {

    "use strict";
    var utils = {
        extend: function(Child, Parent) {
            var F = new function() {};
            F.prototype = Parent.prototype;
            Child.prototype = new F();
            Child.prototype.constructor = Child;
            Child.uber = Parent.prototype;
        },
        expand: function() {
            if (!Function.prototype.bind) {
                Function.prototype.bind = function(oThis) {
                    if (typeof this !== "function") {
                        throw new TypeError("传入绑定对象必须为函数");
                    }
                    var aArgs = Array.prototype.slice.call(arguments, 1),
                        fToBind = this,
                        fNOP = function() {},
                        fBound = function() {
                            return fToBind.apply(this instanceof fNOP && oThis ?
                                this :
                                oThis,
                                aArgs.concat(Array.prototype.slice.call(arguments)));
                        };
                    fNOP.prototype = this.prototype;
                    fBound.prototype = new fNOP();
                    return fBound;
                };
            }
        },
        isIE: {
            ie9: function() {
                if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/9./i) == "9.") {
                    return true;
                } else {
                    return false;
                }
            },
            ie8: function() {
                if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/8./i) == "8.") {
                    return true;
                } else {
                    return false;
                }
            }
        }
    };


    var APP = function() {
        if (typeof APP._initialized == 'undefined') {

            utils.expand();

            APP.prototype.placeholder = function() {
                var ua = navigator.userAgent;
                if (ua.indexOf("MSIE") > 0 && (ua.indexOf("MSIE 6.0") > 0 || ua.indexOf("MSIE 7.0") > 0 || ua.indexOf("MSIE 8.0") > 0 || ua.indexOf("MSIE 9.0") > 0)) {

                    //循环遍历初始化
                    $('input[placeholder],textarea[placeholder]').each(function(k, v) {
                        if ($(v).val() == '') {
                            //如果是密码框
                            if ($(v).attr('type') == 'password') {
                                $(v).before("<input type='text' class='" + $(v).attr("class") + " passwordPlaceHolder' value='" + $(v).attr("placeholder") + "' style='color: #999;'/>").hide().attr('placeholder', '');
                            } else {
                                $(v).val($(v).attr('placeholder')).css('color', '#999').data('init', 'true');
                            }
                        }
                    }).on('focus', function(e) {
                        //如果获取焦点的时候，是显示placeholder
                        if ($(this).data('init') == 'true' && !$(this).attr('readonly')) {
                            $(this).css('color', '#555').data('init', 'false').val('');
                        }
                    }).on('blur', function(e) {
                        if ($(this).attr('type') == 'password' && $(this).val() == '') {
                            $(this).val('').hide().prev().css('display', 'inline-block');
                        } else if ($(this).val() == '') {
                            $(this).val($(this).attr('placeholder')).css('color', '#999').data('init', 'true');
                        }
                    });
                    setTimeout(function(){
                        $('.passwordPlaceHolder').on('focus',function(e){
                            $(this).hide().siblings('input').css('display', 'inline-block').focus();
                        });
                    },100);
                }
            };

            APP.prototype.tab = function(obj) {
                /**参数
                 * obj = {
                 *   el: tab的总容器对象
                 *   btn: tab的事件点击对象的父容器，传入完整的class名字或者id
                 *   content: tab要切换的内容的父容器
                 *   mouseover: true则使用mouseover事件，否则默认使用click事件
                 * }
                 * demo： 
                 *    app.tab({
                 *        el: $('.stab'),
                 *        btn: '.stab-list',
                 *        content: '.stab-content',
                 *        mouseover: true
                 *    });
                 **/
                var obj = obj || {};

                obj.el.each(function(k, v) {
                    var _c0 = (obj.btn ? $(v).find(obj.btn) : $(v).children().eq(0));
                    var _c1 = (obj.content ? $(v).find(obj.content) : $(v).children().eq(1));
                    var _event = obj.mouseover ? 'mouseover' : 'click';
                    _c0.children().on(_event, function(e) {
                        var _index = $(this).index();
                        _c1.children().eq(_index).addClass('active').siblings().removeClass('active');
                    })
                });
            };

            APP.prototype.drop = function(obj) {
                /**
                 * obj = {
                 *    el: 下拉对象
                 *    mouseover: true为使用mouseover事件，false为使用click事件
                 * }
                 **/
                var obj = obj || {};
                var _hideHanle = function(e) {
                    obj.el.find('.sdrop-list').removeClass('active');
                }

                if (obj.mouseover) {
                    obj.el.on('mouseenter', function(e) {
                        obj.el.find('.sdrop-list').addClass('active');
                    });
                    obj.el.on('mouseleave', function(e) {
                        obj.el.find('.sdrop-list').removeClass('active');
                        _hideHanle();
                    });
                } else {
                    var _bodyHandle = function(e) {
                        obj.el.find('.sdrop-list').removeClass('active');
                        $(document.body).off('click', _bodyHandle);
                    }
                    obj.el.find('.sdrop-nav').on('click', function(e) {
                        e.stopPropagation();
                        obj.el.find('.sdrop-list').toggleClass('active');
                        $(document.body).on('click', _bodyHandle);

                    });
                }
                obj.el.find('.sdrop-list').children().on('click', function(e) {
                    var _re = $(this).html();
                    obj.el.find('.sdrop-nav').children().eq(0).html(_re);
                    _hideHanle();
                });
            }

            APP.prototype.wdrop = function(obj) {
                /**
                 * obj = {
                 *    el: 下拉对象
                 *    mouseover: true为使用mouseover事件，false为使用click事件
                 * }
                 **/
                var obj = obj || {};
                var _hideHanle = function(e) {
                    obj.el.find('.wdrop-list').removeClass('active');
                }

                if (obj.mouseover) {
                    obj.el.on('mouseenter', function(e) {
                        obj.el.find('.wdrop-list').addClass('active');
                    });
                    obj.el.on('mouseleave', function(e) {
                        obj.el.find('.wdrop-list').removeClass('active');
                        _hideHanle();
                    });
                } else {
                    var _bodyHandle = function(e) {
                        obj.el.find('.wdrop-list').removeClass('active');
                        $(document.body).off('click', _bodyHandle);
                    }
                    obj.el.find('.wdrop-nav').on('click', function(e) {
                        e.stopPropagation();
                        obj.el.find('.sdrop-list').toggleClass('active');
                        $(document.body).on('click', _bodyHandle);

                    });
                }
                obj.el.find('.sdrop-list').children().on('click', function(e) {
                    var _re = $(this).html();
                    obj.el.find('.sdrop-nav').children().eq(0).html(_re);
                    _hideHanle();
                });
            }

            APP.prototype.checkbox = function(classes, choose, unchoose) {
                classes.each(function(k, v) {
                    if (!$(v).find('i').data('clickevent')) {
                        $(v).find('i').on('click', function(e) {
                            var _p = $(this).parent();
                            if (_p.hasClass('active')) {
                                _p.removeClass('active').children('input').prop('checked', false);
                                unchoose && unchoose();
                            } else {
                                _p.addClass('active').children('input').prop('checked', true);
                                choose && choose();
                            }
                        }).data('clickevent', true);
                    }
                });
            };


            APP.prototype.radio = function(classes) {
                classes.children().on('click', function(e) {
                    $(this).find('i').addClass('active');
                    $(this).find('input').prop('checked', true);
                    $(this).siblings().find('i').removeClass('active')
                    $(this).siblings().find('input').prop('checked', false);

                });
            };

            APP.prototype.radioCB = function(obj) {
                obj.classes.children().on('click', function(e) {
                    $(this).find('i').addClass('active');
                    $(this).find('input').prop('checked', true);
                    $(this).siblings().find('i').removeClass('active')
                    $(this).siblings().find('input').prop('checked', false);
                    obj.cb($(this).find("input").val());
                });
            };

            APP.prototype.select = function(o) {
                // o = {
                //     el: select对象
                //     cb: 回调函数
                //     type: click || mouseover
                // };
                var o = o || {};
                o.el.each(function(k, v) {
                    $(v).on('mouseleave', function(e) {
                        $(this).removeClass('active').find('dt b').attr('class', 'sarrow-down');
                    });
                    if (o.type && o.type == 'mouseover') {
                        $(v).on('mouseenter', function(e) {
                            $(this).addClass('active').find('dt b').attr('class', 'sarrow-up');
                        })
                    } else {
                        $(v).find('dt').on('click', function(e) {
                            var _p = $(this).parent();
                            if (_p.hasClass('active')) {
                                _p.removeClass('active');
                                $(v).find('b').attr('class', 'sarrow-down');
                            } else {
                                _p.addClass('active');
                                $(v).find('b').attr('class', 'sarrow-up');
                            }
                        });
                    }

                    $(v).find('dd').children().on('click', function(e) {
                        var _h = $(this).html();
                        var _dd = $(this).parent();
                        _dd.siblings('dt').find('span').html(_h).siblings('b').attr('class', 'sarrow-down');
                        var _index = $(this).index();
                        var _parent = _dd.parent();
                        _parent.removeClass('active');
                        var _select = _parent.find('select');
                        _select.find('option').eq(_index).prop('selected', true);
                        o.cb && o.cb.call(null, _select.val() || _index);
                    });
                });
            }

            APP.prototype.selectCB = function(o) {
                // o = {
                //     el: select对象
                //     cb: 回调函数
                //     type: click || mouseover
                // };
                var o = o || {};
                var a_html = '',
                    option_html = '';
                if (o.data) {
                    if (o.isbound_bank) {
                        o.data.map(function(item, i) {
                            a_html += '<a href="javascript:;"><em>' + item[o.label_left] + '</em><em class="wgray bm">' + item[o.label_right].bankCardMosaic() + '</em></a>';
                            option_html += '<option>' + item[o.label_left] + '</option>';
                        });
                    } else {
                        o.data.map(function(item, i) {
                            a_html += '<a href="javascript:;">' + item.label + '</a>';
                            option_html += '<option value="' + item.id + '">' + item.label + '</option>';
                        });
                    }

                }

                o.el.find('dd').html(a_html);
                o.el.find('select').html(option_html);
                o.el.each(function(k, v) {
                    $(v).on('mouseleave', function(e) {
                        $(this).removeClass('active').find('dt b').attr('class', 'sarrow-down');
                    });
                    if (o.type && o.type == 'mouseover') {
                        $(v).on('mouseenter', function(e) {
                            $(this).addClass('active').find('dt b').attr('class', 'sarrow-up');
                        })
                    } else {
                        $(v).find('dt').on('click', function(e) {
                            var _p = $(this).parent();
                            if (_p.hasClass('active')) {
                                _p.removeClass('active');
                                $(v).find('b').attr('class', 'sarrow-down');
                            } else {
                                _p.addClass('active');
                                $(v).find('b').attr('class', 'sarrow-up');
                            }
                        });
                    }

                    $(v).find('dd').on('click', "a", function(e) {
                        var _h = $(this).html();
                        var _dd = $(this).parent();
                        _dd.siblings('dt').find('span').html(_h).siblings('b').attr('class', 'sarrow-down');
                        var _index = $(this).index();
                        var _parent = _dd.parent();
                        _parent.removeClass('active');
                        var _select = _parent.find('select');
                        _select.find('option').eq(_index).prop('selected', true);
                        o.cb && o.cb.call(null, o.data[_index]);
                    });
                });
            }

            APP.prototype.editNum = function(el) {
                el.each(function(k, v) {
                    $(v).find('span').on('click', function() {
                        var _input = $(this).siblings('input');
                        var _val = _input.val();
                        if (isNaN(_val) || _val <= 0) {
                            _input.val(1);
                        } else {
                            if ($(this).index() == 0) {
                                _input.val(_val == 1 ? 1 : --_val);
                            } else {
                                _input.val(++_val);
                            }
                        }

                    });
                });
            };

            APP.prototype.calc = {
                floatCal: function(a, b, symbol) {
                    var r1, r2, m;

                    try {
                        var _pc = a.toString().split(".")[1];
                        r1 = _pc ? _pc.length : 0;
                    } catch (e) {
                        r1 = 0
                    };
                    try {
                        var _pc = b.toString().split(".")[1];
                        r2 = _pc ? _pc.length : 0;
                    } catch (e) {
                        r2 = 0
                    };
                    m = Math.pow(10, Math.max(r1, r2));
                    a = a.toString().replace(".", "");
                    b = b.toString().replace(".", "");

                    if (r1 < r2) {
                        a = parseInt(a) * Math.pow(10, (r2 - r1));
                    } else if (r1 > r2) {
                        b = parseInt(b) * Math.pow(10, (r1 - r2));
                    }
                    a = parseInt(a);
                    b = parseInt(b);

                    if (symbol === "+") return (a + b) / m;
                    if (symbol === "-") return (a - b) / m;
                    if (symbol === "*") return (a * b / Math.pow(10, Math.max(r1, r2) * 2));
                    if (symbol === "/") return (a / b);
                },
                add: function(a, b) {
                    return this.floatCal(a, b, '+');
                },
                sub: function(a, b) {
                    return this.floatCal(a, b, '-');
                },
                mul: function(a, b) {
                    return this.floatCal(a, b, '*');
                },
                div: function(a, b) {
                    return this.floatCal(a, b, '/');
                }
            };

            APP.prototype.hint = {
                init: function() {
                    $('body').append(
                        '<div class="spopup" id="shint">' +
                        '<div class="stable">' +
                        '<div class="stable-cell">' +
                        '<div class="spopup-wrapper" id="shint-wrapper">' +
                        '<div class="hint-box">' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>'
                    );
                    return this;

                },
                show: function(obj) {
                    $('#shint').addClass("active");
                    $('#shint').find(".hint-box").addClass(obj.type);
                    $('#shint').find(".hint-box").html(obj.msg);
                    setTimeout(function() {
                        $('#shint-wrapper').addClass('active');
                    });
                    setTimeout(this.hide, 2000, obj.cb);
                },
                hide: function(obj) {
                    $('#shint-wrapper').removeClass('active');
                    $('#shint').removeClass('active');
                }

            };

            APP.prototype.popup = {
                _initbg: function() {
                    if ($('.popup-bg').length == 0) {
                        var _popupbg = document.createElement('div');
                        _popupbg.className = 'spopup-bg';
                        document.body.appendChild(_popupbg);
                    }
                },
                confirm: function() {
                    var confirm_ok_handle = function() {},
                        confirm_cancel_handle = function() {};
                    var _init = function() {
                        var _popup = document.createElement('div');
                        _popup.className = 'spopup';
                        _popup.id = 'sconfirm';
                        _popup.innerHTML =
                            '<div class="stable">' +
                            '<div class="stable-cell">' +
                            '<div class="spopup-wrapper" id="sconfirm-wrapper">' +
                            '<div class="spopup-head active" id="sconfirm-head">' +
                            '<span></span>' +
                            '<i></i>' +
                            '</div>' +
                            '<div class="spopup-content" id="sconfirm-content">' +
                            '</div>' +
                            '<div class="spopup-footer">' +
                            '<span class="spopup-ok" id="sconfirm-ok"></span>' +
                            '<span class="spopup-cancel" id="sconfirm-cancel"></span>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        document.body.appendChild(_popup);
                    };
                    var _initEvent = function() {
                        $('#sconfirm-head i').on('click', function(e) {
                            confirm_cancel_handle.call(this, e);
                        });
                        $('#sconfirm-ok').on('click', function(e) {
                            confirm_ok_handle.call(this, e);
                        });
                        $('#sconfirm-cancel').on('click', function(e) {
                            confirm_cancel_handle.call(this, e);
                        });

                    };

                    this._initbg();
                    _init();
                    _initEvent();

                    return {
                        show: function(obj) {
                            var obj = obj || {};
                            //自定义父样式
                            if (obj.popupClass) {
                                $(".spopup").addClass(obj.popupClass);
                            } else {
                            	$('.spopup').attr('class', 'spopup');
                            }
                            //设置弹框标题
                            $('#sconfirm-head span').html(obj.title || '提示');
                            //设置按钮文字
                            $('#sconfirm-ok').html(obj.confirmText || '确认');
                            $('#sconfirm-cancel').html(obj.cancelText || '取消');

                            //是否显示标题
                            if (obj.nstitle) {
                                $('#sconfirm-head').removeClass('active');
                            } else {
                                $('#sconfirm-head').addClass('active');
                            }

                            //中间内容是否超出隐藏
                            if (obj.contentVisible) {
                                $('#sconfirm-content').addClass('visible');
                            } else {
                                $('#sconfirm-content').removeClass('visible');
                            }

                            //是否显示按钮
                            if (obj.nsbtn) {
                                $('.spopup-footer').hide();
                            } else {
                                $('.spopup-footer').show();
                            }

                            //是否显示确定按钮
                            if (obj.nsconfirm) {
                                $('.spopup-ok').hide();
                            } else {
                                $('.spopup-ok').show();
                            }

                            //是否显示取消按钮
                            if (obj.nscancel) {
                                $('.spopup-cancel').hide();
                            } else {
                                $('.spopup-cancel').show();
                            }


                            //设置确认按钮处理函数
                            if (obj.confirm && typeof obj.confirm == 'function') {
                                confirm_ok_handle = function() {
                                    if (!obj.confirm()) {
                                        this.hide();
                                    };


                                }.bind(this);
                            } else {
                                confirm_ok_handle = function() {
                                    this.hide();
                                }.bind(this);
                            }
                            //设置弹框内容
                            $('#sconfirm-content').html(obj.content || '');
                            //设置弹窗宽高
                            $('#sconfirm-content').css({ 'max-height': (obj.height || 300) - (obj.nstitle ? 70 : 120) });
                            $('#sconfirm-wrapper').width(obj.width || 400).height(obj.height || 300);
                            //设置取消按钮处理函数
                            if (obj.cancel && typeof obj.cancel == 'function') {
                                confirm_cancel_handle = function() {
                                    if (!obj.cancel()) {
                                        this.hide();
                                    }
                                }.bind(this);
                            } else {
                                confirm_cancel_handle = function() {
                                    this.hide();
                                }.bind(this);
                            }

                            $('.spopup-bg').addClass('active');
                            $('#sconfirm').css({ 'top': ($(window).height() - (obj.height || 300)) / 2, 'left': ($(window).width() - (obj.width || 400)) / 2 }).addClass('active');
                            setTimeout(function() {
                                $('#sconfirm-wrapper').addClass('active');
                            });
                        },
                        hide: function() {
                            //判断是否还有其他弹出框显示，如果没有，再关闭背景
                            var _hasOtherShow = 0;
                            $('.spopup').each(function(k,v){
                                if($(v).hasClass('active')){
                                    _hasOtherShow ++;
                                }
                            });
                            if(_hasOtherShow == 1){
                                $('.spopup-bg').removeClass('active');
                            }
                            $('#sconfirm-wrapper').removeClass('active');
                            if (utils.isIE.ie8()) {
                                $('#sconfirm').removeClass('active');
                            } else {
                                setTimeout(function() {
                                    $('#sconfirm').removeClass('active');
                                }, 200);
                            }
                        }
                    }
                },
                alert: function() {
                    var alert_ok_handle = function() {};
                    var _init = function() {
                        var _popup = document.createElement('div');
                        _popup.className = 'spopup';
                        _popup.id = 'salert';
                        _popup.innerHTML =
                            '<div class="stable">' +
                            '<div class="stable-cell">' +
                            '<div class="spopup-wrapper" id="salert-wrapper">' +
                            '<div class="spopup-head active" id="salert-head">' +
                            '<span></span>' +
                            '</div>' +
                            '<div class="spopup-content" id="salert-content">' +
                            '</div>' +
                            '<div class="spopup-footer">' +
                            '<span class="spopup-ok" id="salert-ok"></span>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        document.body.appendChild(_popup);
                    };
                    var _initEvent = function() {
                        $('#salert-ok').on('click', function(e) {
                            alert_ok_handle.call(this, e);
                        });

                    };

                    this._initbg();
                    _init();
                    _initEvent();

                    return {
                        show: function(obj) {
                            var obj = obj || {};
                            //自定义父样式
                            if (obj.popupClass) {
                                $(".spopup").addClass(obj.popupClass);
                            }
                            //设置弹框标题
                            $('#salert-head span').html(obj.title || '提示');
                            //设置按钮文字
                            $('#salert-ok').html(obj.alertText || '确认');

                            //是否显示标题
                            if (obj.nstitle) {
                                $('#salert-head').removeClass('active');
                            } else {
                                $('#salert-head').addClass('active');
                            }

                            //中间内容是否超出隐藏
                            if (obj.contentVisible) {
                                $('#salert-content').addClass('visible');
                            } else {
                                $('#salert-content').removeClass('visible');
                            }

                            //是否显示按钮
                            if (obj.nsbtn) {
                                $('.spopup-footer').hide();
                            } else {
                                $('.spopup-footer').show();
                            }

                            //设置确认按钮处理函数
                            if (obj.alert && typeof obj.alert == 'function') {
                                alert_ok_handle = function() {
                                    if (!obj.alert()) {
                                        this.hide();
                                    };

                                }.bind(this);
                            } else {
                                alert_ok_handle = function() {
                                    this.hide();
                                }.bind(this);
                            }
                            //设置弹框内容
                            $('#salert-content').html(obj.content || '');
                            //设置弹窗宽高
                            $('#salert-content').css({ 'max-height': (obj.height || 300) - (obj.nstitle ? 70 : 120) });
                            $('#salert-wrapper').width(obj.width || 400).height(obj.height || 300);

                            $('.spopup-bg').addClass('active');
                            $('#salert').css({ 'top': ($(window).height() - (obj.height || 300)) / 2, 'left': ($(window).width() - (obj.width || 400)) / 2 }).addClass('active');
                            setTimeout(function() {
                                $('#salert-wrapper').addClass('active');
                            });
                        },
                        hide: function() {
                            //判断是否还有其他弹出框显示，如果没有，再关闭背景
                            var _hasOtherShow = 0;
                            $('.spopup').each(function(k,v){
                                if($(v).hasClass('active')){
                                    _hasOtherShow ++;
                                }
                            });
                            if(_hasOtherShow == 1){ 
                                $('.spopup-bg').removeClass('active');
                            }
                            $('#salert-wrapper').removeClass('active');
                            if (utils.isIE.ie8()) {
                                $('#salert').removeClass('active');
                            } else {
                                setTimeout(function() {
                                    $('#salert').removeClass('active');
                                }, 200);
                            }
                        }
                    }
                }
            };

            APP.prototype.region = function(o) {
                if (!o.el) throw ('请传入地区对象');
                if (!o.data) throw ('请传入地区数据');

                var _provinceIndex = 0,
                    _cityIndex = 0,
                    _areaIndex = 0;

                var _provinceId = '',
                    _cityId = '',
                    _areaId = '';

                var _province = '',
                    _city = '',
                    _area = '';


                o.el.each(function(k, v) {

                    //初始化数据
                        if(o.init) {
                            _provinceId = o.init.provinceId;
                            _cityId = o.init.cityId;
                            _areaId = o.init.areaId;

                            var _html = '<div class="spanel-content">' +
                                        '<div class="spanel-tab">' +
                                        '<i class="spanel-close">&times;</i>' +
                                        '<ul>';
                            for (var i = 0, l = o.data.length; i < l; i++) {
                                var _t = o.data[i];
                                if(_t.region_id == _provinceId) {
                                    _provinceIndex = i;
                                    _province = _t.region_name;
                                    _html += '<li><span>'+_t.region_name+'<span></li>';
                                    for(var a = 0, b= _t.children.length; a < b; a++) {
                                        var _t1 = _t.children[a];
                                        if(_t1.region_id == _cityId) {
                                            _cityIndex = a;
                                            _city = _t1.region_name;
                                            _html += '<li><span>'+_t1.region_name+'<span></li>';
                                            for(var m = 0, n= _t1.children.length; m < n; m++) {
                                                var _t2 = _t1.children[m];
                                                if(_t2.region_id == _areaId) {
                                                    _areaIndex = m;
                                                    _area = _t2.region_name;
                                                    _html += '<li class="active"><span>'+_t2.region_name+'<span></li>';
                                                }
                                            } 
                                        }
                                    }  
                                 }       
                            }   

                            _html += '</ul></div><div class="spanel-list"><ul><li>';
                            var _currentLevel2 = [];
                            var _currentLevel3 = [];
                            for (var i = 0, l = o.data.length; i < l; i++) {
                                var _t = o.data[i];
                                if(_t.region_id == _provinceId) {
                                    _currentLevel2 = _t.children;
                                    _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '" class="active">' + _t.region_name + '</span>')
                                 }  else {
                                    _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.region_name + '</span>')
                                 }     
                            }
                            _html += '</li><li>';
                            for (var i = 0, l = _currentLevel2.length; i < l; i++) {
                                var _t = _currentLevel2[i];
                                if(_t.region_id == _cityId) {
                                    _currentLevel3 = _t.children;
                                    _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '" class="active">' + _t.region_name + '</span>')
                                 }  else {
                                    _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.region_name + '</span>')
                                 }     
                            }
                            _html += '</li><li class="active">';
                            for (var i = 0, l = _currentLevel3.length; i < l; i++) {
                                var _t = _currentLevel3[i];
                                if(_t.region_id == _areaId) {
                                    _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '" class="active">' + _t.region_name + '</span>')
                                 }  else {
                                    _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.region_name + '</span>')
                                 }     
                            }
                            _html += '</li></ul></div></div><div class="spanel-mask"></div>';

                            var _inner = $(v).find('.spanel-wrapper .spanel-inner');
                            if(_inner.length > 0) {
                                _inner.append(_html);
                            } else {
                                $(v).find('.spanel-wrapper').append(_html);
                            }

                        }

                    //遮罩添加事件
                    $(v).on('click', '.spanel-mask', function(e) {
                        e.stopPropagation();
                        $(this).parents('.spanel-wrapper').removeClass('active');
                    });

                    //关闭按钮
                    $(v).on('click', '.spanel-close', function(e) {
                        e.stopPropagation();
                        $(this).parents('.spanel-wrapper').removeClass('active');
                    });
                    //省市区切换
                    $(v).on('click', '.spanel-tab li', function(e) {
                        e.stopPropagation();
                        var _index = $(this).index();
                        $(this).parent().parent().next().find('li').eq(_index).addClass('active').siblings().removeClass('active');
                            $(this).addClass('active').siblings().removeClass('active');
                    });

                    $(v).find('.spanel-key').on('click', function(e) {
                        var _list = $(this).siblings('.spanel-wrapper');
                        //如果显示，则隐藏
                        if (_list.hasClass('active')) {
                            _list.removeClass('active');
                            return;
                        }
                        //检查列表中是否有内容
                        if (_list.find('.spanel-content').length == 0) {
                            var _html = '<div class="spanel-content">' +
                                '<div class="spanel-tab">' +
                                '<i class="spanel-close">&times;</i>' +
                                '<ul>' +
                                '<li class="active"><span>请选择<span></li>' +
                                '</ul>' +
                                '</div>' +
                                '<div class="spanel-list">' +
                                '<ul>' +
                                '<li class="active">';
                            for (var i = 0, l = o.data.length; i < l; i++) {
                                var _t = o.data[i];
                                _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.region_name + '</span>')
                            }
                            _html += '</li>' +
                                '<li>' +
                                '</li>' +
                                '<li>' +
                                '</li>' +
                                '</ul>' +
                                '</div>' +
                                '</div>' +
                                '<div class="spanel-mask"></div>';
                            var _inner = _list.find('.spanel-inner');
                            if(_inner.length > 0) {
                                _inner.append(_html);
                            } else {
                                _list.append(_html);
                            }
                        }

                        //显示地区选择列表
                        $(this).siblings().addClass('active');
                    });
                    $(v).find('.spanel-wrapper').on('click', '.spanel-list span', function(e) {
                        e.stopPropagation();
                        //获取点击的是省市区中的哪一个
                        var _pindex = $(this).parent().index();
                        var _index = $(this).index();

                        $(this).addClass('active').siblings().removeClass('active');
                        //如果是省
                        if (_pindex == 0) {
                            //记录省的索引、id、名称
                            _provinceIndex = _index;
                            _provinceId = $(this).data('id');
                            _province = $(this).html();

                            var _html = '';
                            var _cityData = o.data[_index].children;
                            for (var i = 0, l = _cityData.length; i < l; i++) {
                                var _t = _cityData[i];
                                _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.region_name + '</span>')
                            }
                            $(this).parent().removeClass('active').next().html(_html).addClass('active');

                            $(this).parents('.spanel-wrapper').find('.spanel-tab ul').find('li').remove().end().append('<li><span>' + $(this).html() + '</span></li><li class="active"><span>请选择</span></li>');
                        }
                        //如果是市
                        else if (_pindex == 1) {
                            //记录市的索引、id、名称
                            _cityIndex = _index;
                            _cityId = $(this).data('id');
                            _city = $(this).html();

                            var _html = '';
                            var _cityData = o.data[_provinceIndex].children[_index].children;
                            for (var i = 0, l = _cityData.length; i < l; i++) {
                                var _t = _cityData[i];
                                _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.region_name + '</span>')
                            }
                            $(this).parent().removeClass('active').next().html(_html).addClass('active');

                            $(this).parents('.spanel-wrapper').find('.spanel-tab ul li:gt(0)').remove();
                            $(this).parents('.spanel-wrapper').find('.spanel-tab ul li').eq(0).after('<li><span>' + $(this).html() + '</span></li><li class="active"><span>请选择</span></li>');
                        }
                        //如果是区
                        else {
                            //记录区的索引、id、名称
                            _areaIndex = _index;
                            _areaId = $(this).data('id');
                            _area = $(this).html();

                            $(this).parents('.spanel-wrapper').find('.spanel-tab ul li').last().html('<span>' + $(this).html() + '</span>');
                            //隐藏地区列表
                            $(this).parents('.spanel-wrapper').removeClass('active');

                            //执行回调
                            if (o.cb) {
                                var _cbArg = {
                                    provinceIndex: _provinceIndex,
                                    provinceId: _provinceId,
                                    province: _province,
                                    cityIndex: _cityIndex,
                                    cityId: _cityId,
                                    city: _city,
                                    areaIndex: _areaIndex,
                                    areaId: _areaId,
                                    area: _area,
                                    index: k
                                };
                                if ((typeof o.cb) == 'function') {
                                    o.cb.call(null, _cbArg);
                                } else {
                                    o.cb[k] && o.cb[k].call(null, _cbArg);
                                }
                            }
                        }
                    });
                });

            };


            // 四级显示
            APP.prototype.region2 = function(o) {
                if (!o.el) throw ('请传入地区对象');
                // if (!o.province_data) throw ('请传入省份数据');
                // var province_data = o.province_data;
                // 获取下级数据

                function getCity(o) {
                    var url = "/api/common/region/area-data?type=2&region_id=" + o.id;
                    $.get(url, function(res) {
                        if (res.error_code == 0) {
                            o.cb(res.data);
                        }
                    });
                }
                function getArea(o) {
                    var url = "/api/common/region/area-data?type=3&region_id=" + o.id;
                    $.get(url, function(res) {
                        if (res.error_code == 0) {
                            o.cb(res.data);
                        }
                    });
                }
                function getTown(o) {
                    var url = "/api/common/region/area-data?type=4&region_id=" + o.id;
                    $.get(url, function(res) {
                        if (res.error_code == 0) {
                            o.cb(res.data);
                        }
                    });
                }

                function getProvince(cb) {
                    var url = "/api/common/region/area-data";
                    $.get(url, function(res) {
                        if (res.error_code == 0) {
                            var data = res.data;
                            cb(data);
                        }
                    });
                }

                function regionMain(pdata) {
                    var _provinceIndex = 0,
                        _cityIndex = 0,
                        _areaIndex = 0,
                        _townIndex = 0;

                    var _provinceId = '',
                        _cityId = '',
                        _areaId = '',
                        _townId = '';

                    var _province = '',
                        _city = '',
                        _area = '',
                        _town = '';

                    var province_data = [];
                    province_data = pdata;
                    console.log(province_data);

                    o.el.each(function(k, v) {

                        //初始化数据
                        if(o.init) {
                            _provinceId = o.init.provinceId;
                            _cityId = o.init.cityId;
                            _areaId = o.init.areaId;
                            _townId = o.init.townId;

                            // var city_data = getCity(_provinceId);
                            // var area_data = getArea(_cityId);
                            // var town_data = getTown(_areaId);

                            var _html = '<div class="spanel-content">' +
                                        '<div class="spanel-tab">' +
                                        '<i class="spanel-close">&times;</i>' +
                                        '<ul>';
                            getTabel();
                            function getTabel() {
                                for (var i = 0, l = province_data.length; i < l; i++) {
                                    var _t = province_data[i];
                                    if(_t.region_id == _provinceId) {
                                        _provinceIndex = i;
                                        _province = _t.provice_name;
                                        _html += '<li><span>'+_t.provice_name+'<span></li>';
                                        getCity({
                                            id: _provinceId,
                                            cb: function(res1) {
                                                var city_data = res1;
                                                for(var a = 0, b= city_data.length; a < b; a++) {
                                                    var _t1 = city_data[a];
                                                    if(_t1.region_id == _cityId) {
                                                        _cityIndex = a;
                                                        _city = _t1.city_name;
                                                        _html += '<li><span>'+_t1.city_name+'<span></li>';
                                                        getArea({
                                                            id: _cityId,
                                                            cb: function(res2) {
                                                                var area_data = res2;
                                                                for(var m = 0, n= area_data.length; m < n; m++) {
                                                                    var _t2 = area_data[m];
                                                                    if(_t2.region_id == _areaId) {
                                                                        _areaIndex = m;
                                                                        _area = _t2.county_name;
                                                                        _html += '<li><span>'+_t2.county_name+'<span></li>';
                                                                        getTown({
                                                                            id: _areaId,
                                                                            cb: function(res3) {
                                                                                var town_data = res3;
                                                                                for(var y = 0, z = town_data.length; y < z; y++) {
                                                                                    var _t3 = town_data[y];
                                                                                    if(_t3.region_id == _townId) {
                                                                                        _areaIndex = y;
                                                                                        _area = _t3.town_name;
                                                                                        _html += '<li class="active"><span>'+_t3.town_name+'<span></li>';
                                                                                    }
                                                                                }
                                                                                getList();
                                                                            }
                                                                        });
                                                                        
                                                                    }
                                                                }
                                                            }
                                                        });
                                                         
                                                    }
                                                } 
                                            }
                                        });
                                     }       
                                }
                            }
                            
                            function getList() {
                                _html += '</ul></div><div class="spanel-list"><ul><li>';
                                for (var i = 0, l = province_data.length; i < l; i++) {
                                    var _t = province_data[i];
                                    if(_t.region_id == _provinceId) {
                                        _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '" class="active">' + _t.provice_name + '</span>')
                                     }  else {
                                        _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.provice_name + '</span>')
                                     }     
                                }
                                _html += '</li><li>';
                                getCity({
                                    id: _provinceId,
                                    cb: function(res10) {
                                        var city_data = res10;
                                        for (var i = 0, l = city_data.length; i < l; i++) {
                                            var _t = city_data[i];
                                            if(_t.region_id == _cityId) {
                                                _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '" class="active">' + _t.city_name + '</span>')
                                             }  else {
                                                _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.city_name + '</span>')
                                             }     
                                        }

                                        _html += '</li><li>';
                                        getArea({
                                            id: _cityId,
                                            cb: function(res11) {
                                                var area_data = res11;
                                                for (var i = 0, l = area_data.length; i < l; i++) {
                                                    var _t = area_data[i];
                                                    if(_t.region_id == _areaId) {
                                                        _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '" class="active">' + _t.county_name + '</span>')
                                                     }  else {
                                                        _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.county_name + '</span>')
                                                     }     
                                                }

                                                _html += '</li><li class="active">';
                                                getTown({
                                                    id: _areaId,
                                                    cb: function(res12) {
                                                        var town_data = res12;
                                                        for (var i = 0, l = town_data.length; i < l; i++) {
                                                            var _t = town_data[i];
                                                            if(_t.region_id == _townId) {
                                                                _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '" class="active">' + _t.town_name + '</span>')
                                                             }  else {
                                                                _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.town_name + '</span>')
                                                             }     
                                                        }

                                                        _html += '</li></ul></div></div><div class="spanel-mask"></div>';
                                                        var _inner = $(v).find('.spanel-wrapper .spanel-inner');
                                                        if(_inner.length > 0) {

                                                            _inner.append(_html);
                                                        } else {
                                                            $(v).find('.spanel-wrapper').append(_html);
                                                        }
                                                    }
                                                });
                                            }
                                        });
                                    }
                                });  
                            }
                                
                        }

                        //遮罩添加事件
                        $(v).on('click', '.spanel-mask', function(e) {
                            e.stopPropagation();
                            $(this).parents('.spanel-wrapper').removeClass('active');
                        });

                        //关闭按钮
                        $(v).on('click', '.spanel-close', function(e) {
                            e.stopPropagation();
                            $(this).parents('.spanel-wrapper').removeClass('active');
                        });
                        //省市区切换
                        $(v).on('click', '.spanel-tab li', function(e) {
                            e.stopPropagation();
                            var _index = $(this).index();
                            $(this).parent().parent().next().find('li').eq(_index).addClass('active').siblings().removeClass('active');
                                $(this).addClass('active').siblings().removeClass('active');
                        });

                        $(v).find('.spanel-key').on('click', function(e) {
                            var _list = $(this).siblings('.spanel-wrapper');
                            //如果显示，则隐藏
                            if (_list.hasClass('active')) {
                                _list.removeClass('active');
                                return;
                            }
                            //检查列表中是否有内容
                            if (_list.find('.spanel-content').length == 0) {
                                var _html = '<div class="spanel-content">' +
                                    '<div class="spanel-tab">' +
                                    '<i class="spanel-close">&times;</i>' +
                                    '<ul>' +
                                    '<li class="active"><span>请选择<span></li>' +
                                    '</ul>' +
                                    '</div>' +
                                    '<div class="spanel-list">' +
                                    '<ul>' +
                                    '<li class="active">';

                                for (var i = 0, l = province_data.length; i < l; i++) {
                                    var _t = province_data[i];
                                    _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.provice_name + '</span>')
                                }
                                _html += '</li>' +
                                    '<li>' +
                                    '</li>' +
                                    '<li>' +
                                    '</li>' +
                                    '<li>' +
                                    '</li>' +
                                    '</ul>' +
                                    '</div>' +
                                    '</div>' +
                                    '<div class="spanel-mask"></div>';
                                var _inner = _list.find('.spanel-inner');
                                if(_inner.length > 0) {
                                    _inner.append(_html);
                                } else {
                                    _list.append(_html);
                                }
                            }

                            //显示地区选择列表
                            $(this).siblings().addClass('active');
                        });
                        $(v).find('.spanel-wrapper').on('click', '.spanel-list span', function(e) {
                            e.stopPropagation();
                            //获取点击的是省市区中的哪一个
                            var _pindex = $(this).parent().index();
                            var _index = $(this).index();
                            var _this = $(this);

                            $(this).addClass('active').siblings().removeClass('active');
                            //如果是省
                            if (_pindex == 0) {
                                //记录省的索引、id、名称
                                _provinceIndex = _index;
                                _provinceId = $(this).data('id');
                                _province = $(this).html();

                                var _html = '';
                                getCity({
                                    id: _provinceId,
                                    cb: function(v) {
                                        var _cityData = v;
                                        for (var i = 0, l = _cityData.length; i < l; i++) {
                                            var _t = _cityData[i];
                                            _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.city_name + '</span>')
                                        }
                                        _this.parent().removeClass('active').next().html(_html).addClass('active');

                                        _this.parents('.spanel-wrapper').find('.spanel-tab ul').find('li').remove().end().append('<li><span>' + _this.html() + '</span></li><li class="active"><span>请选择</span></li>');
                                    }
                                });
                                
                            }
                            //如果是市
                            else if (_pindex == 1) {
                                //记录市的索引、id、名称
                                _cityIndex = _index;
                                _cityId = $(this).data('id');
                                _city = $(this).html();

                                var _html = '';
                                getArea({
                                    id: _cityId,
                                    cb: function(v) {
                                        var _areaData = v;
                                        for (var i = 0, l = _areaData.length; i < l; i++) {
                                            var _t = _areaData[i];
                                            _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.county_name + '</span>')
                                        }
                                        _this.parent().removeClass('active').next().html(_html).addClass('active');

                                        _this.parents('.spanel-wrapper').find('.spanel-tab ul li:gt(0)').remove();
                                        _this.parents('.spanel-wrapper').find('.spanel-tab ul li').eq(0).after('<li><span>' + _this.html() + '</span></li><li class="active"><span>请选择</span></li>');
                                    }
                                });
                                
                            }
                            //如果是区,县
                            else if (_pindex == 2) {
                                _areaIndex = _index;
                                _areaId = $(this).data('id');
                                _area = $(this).html();

                                var _html = '';
                                getTown({
                                    id: _areaId,
                                    cb: function(v) {
                                        var _townData = v;
                                        for (var i = 0, l = _townData.length; i < l; i++) {
                                            var _t = _townData[i];
                                            _html += ('<span data-id="' + _t.region_id + '" data-pid="' + _t.parent_id + '">' + _t.town_name + '</span>')
                                        }
                                        _this.parent().removeClass('active').next().html(_html).addClass('active');

                                        _this.parents('.spanel-wrapper').find('.spanel-tab ul li:gt(1)').remove();
                                        _this.parents('.spanel-wrapper').find('.spanel-tab ul li').eq(1).after('<li><span>' + _this.html() + '</span></li><li class="active"><span>请选择</span></li>');
                                    }
                                });
                            }
                            //如果是镇
                            else {
                                //记录区的索引、id、名称
                                _townIndex = _index;
                                _townId = $(this).data('id');
                                _town = $(this).html();

                                $(this).parents('.spanel-wrapper').find('.spanel-tab ul li').last().html('<span>' + $(this).html() + '</span>');
                                //隐藏地区列表
                                $(this).parents('.spanel-wrapper').removeClass('active');

                                //执行回调
                                if (o.cb) {
                                    var _cbArg = {
                                        provinceIndex: _provinceIndex,
                                        provinceId: _provinceId,
                                        province: _province,
                                        cityIndex: _cityIndex,
                                        cityId: _cityId,
                                        city: _city,
                                        areaIndex: _areaIndex,
                                        areaId: _areaId,
                                        area: _area,
                                        townIndex: _townIndex,
                                        townId: _townId,
                                        town: _town,
                                        index: k
                                    };
                                    if ((typeof o.cb) == 'function') {
                                        o.cb.call(null, _cbArg);
                                    } else {
                                        o.cb[k] && o.cb[k].call(null, _cbArg);
                                    }
                                }
                            }
                        });
                    });

                }
                getProvince(regionMain);
                
            };

            APP._initialized = true;
        }
    };

    win.APP = APP;
})(window);
